<template>
  <div class="minPageCon">
      <div class="des">
          <p v-if="userType=='personal'">전문가가 도와주는</br>당신의 2번째 커리어,</br><b>지금 시작해볼까요?</b></p>
          <p v-else>기업에서 필요로하는</br>경력이 풍부한 인재,</br><b>지금 만나볼까요?</b></p>
          <img src="@images/login_bg.png" alt="">
      </div>
      <div class="box">
        <h1>아이디 찾기</h1>
        <p class="info">
          가입시 입력한<br/>
          <b>휴대폰 번호</b>를<br/>
          입력하세요.
        </p>
        <el-form class="loginFrm forgotFrm" :model="forgotFrm" :rules="rules" ref="forgotFrm">
            <el-form-item prop="phone" :error="errors.phone">
              <el-col :span="17">
                <el-input placeholder="휴대폰번호(‘-’는 빼고 입력해주세요)" v-model="forgotFrm.phone" autocomplete="off"></el-input>
              </el-col>
              <el-col :span="7">
                <el-button class="minBtn" v-show="showTime" @click="sendCode" plain>인증번호발송</el-button>
                <el-button class="minBtn" v-show="!showTime" disabled>{{sendTime}}초</el-button>
              </el-col>
            </el-form-item>
            <el-form-item prop="verification_code" :error="errors.ver_code">
              <el-col :span="17">
                <el-input type="number" placeholder="인증번호6자리" v-model="forgotFrm.verification_code" autocomplete="off"></el-input>
              </el-col>
            </el-form-item>
            <el-form-item>
                <el-button :loading="loading" type="primary" class="subBtn" @click="submitForm('forgotFrm')">확인</el-button>
            </el-form-item>
        </el-form>
      </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { retrieveID,sendVerCodeByID } from '@/api';
import { Local } from '@/utils'

export default {
  name:'',
  components:{},
  props:[],
  data(){
      let _this = this;
      var validateMobile = (rule, value, callback) => {
        if (value==='') {
          callback(new Error('휴대폰번호를 입력해주세요.'));
        } else if(!value.match( /^[0-9]{3}[0-9]{4}[0-9]{4}$/ )) {
          callback(new Error('정상적인 전화번호를 입력해주세요.'));
        }else{
          if(_this.errors.phone){
            callback(new Error(_this.errors.phone));
          }else{
            callback();
          }
        }
      };
    return {
      userType:'',
      loading:false,
      showTime: true,
      sendTime: '',
      timer: null,
      errors:{
        phone:'',
        ver_code:''
      },
      forgotFrm: {
        phone:'',
        verification_code:'',
      },
      rules: {
        phone: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ],
        verification_code: [
          { required: true, message: '인증번호를 입력해주세요.', trigger: 'change' }
        ],
      }
    }
  },
  computed:{},
  created(){
    this.userType = this.$route.query.userType || 'personal';
  },
  updated () {
  },
  mounted(){},
  methods:{
      ...mapActions(['setToken','setEmail','setRegDate']),
      submitForm(formName) {
        let that=this;
        this.$refs[formName].validate(async (valid,error) => {
          if (valid) {
            that.loading = true;
            let res = await retrieveID(that.forgotFrm);
            if (res.code == 200) {
              that.loading = false;
              that.setEmail(res.data.email);
              that.setRegDate(res.data.created_at);
              Local.set('email',res.data.email);
              Local.set('regDate',res.data.created_at);
              that.$router.replace({ path:'/forgotRes',query:{userType:that.userType}})
            }else{
              that.loading = false;
              that.errors.ver_code="인증번호가 틀렸습니다. 다시한번 확인해주세요."
            }
          } else {
            return false;
          }
        });
      },
      sendCode(){
        let _this=this;
        if(this.errors.phone){
          _this._send();
          return false;
        }
        this.$refs.forgotFrm.validateField('phone',function(err){
          if(err===''){
            _this._send();
          }
        });
      },
      async _send(){
          let res = await sendVerCodeByID({phone:this.forgotFrm.phone});
          if (res.code == 200) {
            const TIME_COUNT = 180;
            if (!this.timer) {
                this.sendTime = TIME_COUNT;
                this.showTime = false;
                this.timer = setInterval(() => {
                if (this.sendTime > 0 && this.sendTime <= TIME_COUNT) {
                    this.sendTime--;
                } else {
                    this.showTime = true;
                    clearInterval(this.timer);
                    this.timer = null;
                }
                }, 1000);
            }
            this.errors.phone='';
          }else{
            if(res.code == -600){
              this.errors.phone="작성된 휴대폰 번호로 가입된 사용자가 없습니다."
            }else{
              this.errors.ver_code="이미 가입한 휴대폰번호 입니다."
            }
          }
      }
  },
  watch:{}
}
</script>
<style lang="scss" scoped>
  @import "css/user.scss";
</style>
